
package com.be.beadmin.product.impl;

import com.be.beadmin.basicData.entity.User;
import com.be.beadmin.basicData.repository.UserRepository;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaQueryBuilderNew;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.product.dto.input.WorkHoursRequestDto;
import com.be.beadmin.product.dto.input.WorkHoursRequestSimpDto;
import com.be.beadmin.product.dto.output.WorkHoursRequestEx;
import com.be.beadmin.product.entity.*;
import com.be.beadmin.product.mapper.WorkHoursRequestMapper;
import com.be.beadmin.product.mapper.WorkHoursRequestMapperEx;
import com.be.beadmin.product.repository.ProductManufactInforRepository;
import com.be.beadmin.product.repository.WorkHoursRequestHstRepository;
import com.be.beadmin.product.repository.WorkHoursRequestRepository;
import com.be.beadmin.product.service.WorkHoursRequestService;
import com.be.beadmin.project.entity.Info;
import com.be.beadmin.project.entity.TeamInfo;
import com.be.beadmin.project.repository.InfoRepository;
import com.be.beadmin.project.repository.TeamInfoRepository;
import com.be.beadmin.service.entity.NotifyInfo;
import com.be.beadmin.service.entity.NotifyTemplateInfo;
import com.be.beadmin.service.impl.WebSocketNotifyService;
import com.be.beadmin.service.repository.NotifyInfoRepository;
import com.be.beadmin.service.repository.NotifyTemplateInfoRepository;
import com.be.beadmin.service.service.NotifyTemplateInfoService;
import com.be.beadmin.service.service.SerialNumberService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @description 服务实现
* @author ljh
* @date 2023-04-18
**/
@Service
@RequiredArgsConstructor
public class WorkHoursRequestServiceImpl implements WorkHoursRequestService {

    @Autowired
    private  WorkHoursRequestRepository workHoursRequestRepository;
    @Autowired
    private  WorkHoursRequestMapper workHoursRequestMapper;
    @Autowired
    private  WorkHoursRequestMapperEx workHoursRequestExMapper;
    @Autowired
    private WorkHoursRequestHstRepository workHoursRequestHstRepository;

    @Autowired
    private ProductManufactInforRepository productManufactInforRepository;

    @Autowired
    private SerialNumberService serialNumberService;

    @Autowired
    private NotifyTemplateInfoService notifyTemplateInfoService;

    @Autowired
    private NotifyInfoRepository notifyInfoRepository;

    @Autowired
    private InfoRepository infoRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private TeamInfoRepository teamInfoRepository;

    @Override
    public Page<WorkHoursRequestEx> getWorkHoursRequestByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<WorkHoursRequest> page = workHoursRequestRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(WorkHoursRequest_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(WorkHoursRequest_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<WorkHoursRequestEx> page1 = page.map(workHoursRequestExMapper::toEntity);
            return page1;

    }

    @Transactional
    @Override
    public void addWorkHoursRequest(WorkHoursRequestSimpDto workHoursRequestSimpDto) {

            // T_OM_ProcessOperateHst
            //if () throw new BeadminException("该工序尚未结束，不能进行补录！");
            //if () throw new BeadminException("工时补录不能跨月！");
            WorkHoursRequestDto workHoursRequestDto = new WorkHoursRequestDto();
            ProductManufactInfor productManufactInfor = productManufactInforRepository.findProductManufactInforById(workHoursRequestSimpDto.getTaskId());

            if(workHoursRequestSimpDto.getRequestManId()!=null)workHoursRequestDto.setRequestManId(workHoursRequestSimpDto.getRequestManId());
            if(workHoursRequestSimpDto.getApproveManId()!=null)workHoursRequestDto.setApproveManId(workHoursRequestSimpDto.getApproveManId());

            workHoursRequestDto.setRequestType(0);
            Info info = infoRepository.findInfoByProjectCodeAndProjectNameAndDelete(productManufactInfor.getProjectCode(),productManufactInfor.getProjectName(),0);
            if(info!=null)workHoursRequestDto.setProjectId(info.getId());
            workHoursRequestDto.setProjectCode(productManufactInfor.getProjectCode());
            workHoursRequestDto.setProjectName(productManufactInfor.getProjectName());

            workHoursRequestDto.setWo(workHoursRequestSimpDto.getWo());
            workHoursRequestDto.setTaskId(workHoursRequestSimpDto.getTaskId());
//            workHoursRequestDto.setRequestId(requestId);
            workHoursRequestDto.setProductCode(productManufactInfor.getBatchProductCode());
            workHoursRequestDto.setProcessCode(productManufactInfor.getProcessCode());
            workHoursRequestDto.setProcessSequence(String.valueOf(productManufactInfor.getSequence()));
            workHoursRequestDto.setProcessName(productManufactInfor.getProcessName());
            workHoursRequestDto.setStatus(1);//未审核
            workHoursRequestDto.setStandManufactWorkhour(productManufactInfor.getStandManufactWorkhour());
            workHoursRequestDto.setRequestWorkHours(workHoursRequestSimpDto.getRequestWorkHours());
            workHoursRequestDto.setRequestMan(workHoursRequestSimpDto.getRequestMan());
            workHoursRequestDto.setRequestMemo(workHoursRequestSimpDto.getRequestMemo());
            workHoursRequestDto.setApproveMan(workHoursRequestSimpDto.getApproveMan());
            workHoursRequestDto.setManufactStartDate(workHoursRequestSimpDto.getManufactStartDate());
            workHoursRequestDto.setManufactEndDate(workHoursRequestSimpDto.getManufactEndDate());

            WorkHoursRequest workHoursRequest = workHoursRequestMapper.toEntity(workHoursRequestDto);
            workHoursRequestRepository.save(workHoursRequest);

            WorkHoursRequestHst workHoursRequestHst = new WorkHoursRequestHst();

            if(workHoursRequestSimpDto.getRequestManId()!=null)workHoursRequestHst.setRequestManId(workHoursRequestSimpDto.getRequestManId());
            if(workHoursRequestSimpDto.getApproveManId()!=null)workHoursRequestHst.setApproveManId(workHoursRequestSimpDto.getApproveManId());

            workHoursRequestDto.setRequestType(0);
            if(workHoursRequestDto.getProjectId()!=null) workHoursRequestHst.setProjectId(workHoursRequestDto.getProjectId());
            workHoursRequestHst.setProjectCode(workHoursRequestDto.getProjectCode());
            workHoursRequestHst.setProjectName(workHoursRequestDto.getProjectName());

            workHoursRequestHst.setWo(workHoursRequestDto.getWo());
            workHoursRequestHst.setTaskId(workHoursRequestDto.getTaskId());
//            workHoursRequestHst.setRequestId(workHoursRequest.getRequestId());
            workHoursRequestHst.setProductCode(workHoursRequest.getProductCode());
            workHoursRequestHst.setProcessSequence(workHoursRequest.getProcessSequence());
            workHoursRequestHst.setProcessCode(workHoursRequest.getProcessCode());
            workHoursRequestHst.setProcessName(workHoursRequest.getProcessName());
            workHoursRequestHst.setStatus(workHoursRequest.getStatus());
            workHoursRequestHst.setStandManufactWorkhour(workHoursRequest.getStandManufactWorkhour());
            workHoursRequestHst.setRequestWorkHours(workHoursRequest.getRequestWorkHours());
            workHoursRequestHst.setRequestMan(workHoursRequest.getRequestMan());
            workHoursRequestHst.setRequestMemo(workHoursRequest.getRequestMemo());
            workHoursRequestHst.setOperator(workHoursRequest.getApproveMan());
            workHoursRequestHst.setManufactStartDate(workHoursRequest.getManufactStartDate());
            workHoursRequestHst.setManufactEndDate(workHoursRequest.getManufactEndDate());

            workHoursRequestHst= workHoursRequestHstRepository.save(workHoursRequestHst);

            //-----------------------------------------------------------------------
            // 申请人 发送 工时补录 待办给  审批人
            NotifyInfo notifyInfo =new NotifyInfo();
            notifyInfo.setModuleName("生产制造");
            notifyInfo.setFuncName("工单工时填报");
            notifyInfo.setNotifyDesc("项目名称为["+workHoursRequestDto.getProjectName()+"],工单号为["+workHoursRequestDto.getWo()+"],工序为["+workHoursRequest.getProcessName()+"]--工单工时补录申请待审核");
            notifyInfo.setNotifyType("待办");
            notifyInfo.setSenderName(workHoursRequest.getRequestMan());
            notifyInfo.setSendTime(workHoursRequestHst.getCreateTime());
            notifyInfo.setSenderId(workHoursRequestHst.getRequestManId());
            String receiverId = workHoursRequest.getApproveManId();
            // 工时审核没有 用户id字段，用的用户名
            notifyInfo = notifyInfoRepository.save(notifyInfo);

            notifyTemplateInfoService.sendNotify(notifyInfo,-2,workHoursRequestHst.getOperator(),receiverId);
    }

    @Override
    public void updateWorkHoursRequest(WorkHoursRequestDto workHoursRequestDto) {
            WorkHoursRequest workHoursRequest = workHoursRequestRepository.findWorkHoursRequestById(workHoursRequestDto.getId());
            workHoursRequest = workHoursRequestMapper.toEntity(workHoursRequestDto);
            workHoursRequestRepository.save(workHoursRequest);
    }


    @Override
    public void delWorkHoursRequest(String id) {
        WorkHoursRequest workHoursRequest = workHoursRequestRepository.findWorkHoursRequestById(id);
        workHoursRequest.setDelete(1);
        workHoursRequestRepository.save(workHoursRequest);
    }

    @Override
    public void delWorkHoursRequests (List<String> ids) { }

    @Override
    public List<Float> getStandardHoursByWo(String wo) {
        return workHoursRequestRepository.getHours(wo);
    }

    @Override
    public void addWorkHoursRequestOfProject(WorkHoursRequestSimpDto workHoursRequestSimpDto) {
        WorkHoursRequestDto workHoursRequestDto = new WorkHoursRequestDto();

        if(workHoursRequestSimpDto.getRequestManId()!=null)workHoursRequestDto.setRequestManId(workHoursRequestSimpDto.getRequestManId());
        if(workHoursRequestSimpDto.getApproveManId()!=null)workHoursRequestDto.setApproveManId(workHoursRequestSimpDto.getApproveManId());

        workHoursRequestDto.setRequestType(1);
        workHoursRequestDto.setProjectId(workHoursRequestSimpDto.getProjectId());
        workHoursRequestDto.setProjectCode(workHoursRequestSimpDto.getProjectCode());
        workHoursRequestDto.setProjectName(workHoursRequestSimpDto.getProjectName());

        workHoursRequestDto.setStatus(1);//未审核

        workHoursRequestDto.setRequestWorkHours(workHoursRequestSimpDto.getRequestWorkHours());
        workHoursRequestDto.setRequestMan(workHoursRequestSimpDto.getRequestMan());
        workHoursRequestDto.setRequestMemo(workHoursRequestSimpDto.getRequestMemo());
        workHoursRequestDto.setApproveMan(workHoursRequestSimpDto.getApproveMan());

        WorkHoursRequest workHoursRequest = workHoursRequestMapper.toEntity(workHoursRequestDto);
        workHoursRequestRepository.save(workHoursRequest);

        WorkHoursRequestHst workHoursRequestHst = new WorkHoursRequestHst();

        workHoursRequestDto.setRequestType(1);

        if(workHoursRequestSimpDto.getRequestManId()!=null)workHoursRequestHst.setRequestManId(workHoursRequestSimpDto.getRequestManId());
        if(workHoursRequestSimpDto.getApproveManId()!=null)workHoursRequestHst.setApproveManId(workHoursRequestSimpDto.getApproveManId());

        workHoursRequestHst.setProjectId(workHoursRequestSimpDto.getProjectId());
        workHoursRequestHst.setProjectCode(workHoursRequestDto.getProjectCode());
        workHoursRequestHst.setProjectName(workHoursRequestDto.getProjectName());

        workHoursRequestHst.setStatus(workHoursRequest.getStatus());

        workHoursRequestHst.setRequestWorkHours(workHoursRequest.getRequestWorkHours());
        workHoursRequestHst.setRequestMan(workHoursRequest.getRequestMan());
        workHoursRequestHst.setRequestMemo(workHoursRequest.getRequestMemo());
        workHoursRequestHst.setOperator(workHoursRequest.getApproveMan());

        workHoursRequestHst= workHoursRequestHstRepository.save(workHoursRequestHst);

        //-----------------------------------------------------------------------
        // 申请人 发送 工时补录 待办给  审批人
        NotifyInfo notifyInfo =new NotifyInfo();
        notifyInfo.setModuleName("生产制造");
        notifyInfo.setFuncName("项目工时填报");
        notifyInfo.setNotifyDesc("项目号为["+workHoursRequestDto.getProjectCode()+"],填报人为["+workHoursRequest.getRequestMan()+"]--项目工时填报申请待审核");
        notifyInfo.setNotifyType("待办");
        notifyInfo.setSenderName(workHoursRequest.getRequestMan());
        notifyInfo.setSendTime(workHoursRequestHst.getCreateTime());
        notifyInfo.setSenderId(workHoursRequestHst.getRequestManId());
        String receiverId = workHoursRequest.getApproveManId();
        // 工时审核没有 用户id字段，用的用户名
        notifyInfo = notifyInfoRepository.save(notifyInfo);

        notifyTemplateInfoService.sendNotify(notifyInfo,-2,workHoursRequestHst.getOperator(),receiverId);
    }

    @Override
    public User getProjectManufactManager(String projectId) {
        Info info = infoRepository.findInfoByIdAndDelete(projectId,0);
        String teamId = info.getTeamId();
        TeamInfo teamInfo = teamInfoRepository.findTeamInfoByTeamIdAndCategoryAndDelete(teamId,"生产经理", 0);
        if(teamInfo==null) throw new BeadminException("项目团队缺少生产经理");
        else{
            return userRepository.findUserByIdAndDelete(teamInfo.getUserId(), 0);
        }
    }
}